package com.zyjc.city.job;

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author ckj
 * @date 2024年03月31日 13:53
 */
public class ThreadPoolExample {
    public static void main(String[] args) {
        int corePoolSize = 4;
        int maxPoolSize = 10;
        int queueCapacity = 100;

        // 创建线程池，并指定自定义的拒绝策略
        ThreadPoolExecutor executor = new ThreadPoolExecutor(
                corePoolSize,
                maxPoolSize,
                0L,
                TimeUnit.MILLISECONDS,
                new LinkedBlockingQueue<>(queueCapacity),
                new MyRejectedExecutionHandler() // 自定义的拒绝策略
        );

        // 提交任务给线程池
        for (int i = 0; i < 1000; i++) {
            executor.submit(new MyTask(i));
        }

        // 关闭线程池
        executor.shutdown();
    }

    static class MyTask implements Runnable {
        private int taskId;

        public MyTask(int taskId) {
            this.taskId = taskId;
        }

        @Override
        public void run() {
            System.out.println("Executing task " + taskId + " on thread " + Thread.currentThread().getName());
            // 执行具体的任务逻辑
        }
    }

    static class MyRejectedExecutionHandler implements RejectedExecutionHandler {
        @Override
        public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
            // 自定义的拒绝策略逻辑
            System.out.println("Task rejected. Do something here.");
        }
    }
}
